<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-05-14 16:40:00
 * @Last Modified by:   zhaozilong
 * @Last Modified time: 2019-02-20 10:54:29
 * 事件逻辑
 */

namespace app\weixin_manage\logic;
use app\common\logic\Base as BaseLogic;

class Event extends BaseLogic {

	protected function initialize() {
        parent::initialize();

		$this->eventDao = model('weixin_manage/WeixinEvent');
	}

	//点击菜单拉取消息
    public function getEventByKey($wid, $openid, $fromKey) {
		// //删除该用户获取的信息
		// $map = array(
		// 	'openid'	=> $openid,
		// );
		// $this->PollVerify->where($map)->delete();

		// //添加该用户的验证
		// $code = num_rand(20);
		// $data = array(
		// 	'openid' 		=> $openid,
		// 	'code'			=> $code,
		// 	'text'			=> $text,
		// 	'create_time'	=> time(),
		// );
		// $this->PollVerify->add($data);

		db('Aaaa')->insert(['space'=>'weixin', 'module'=>'event', 'flag'=>'event_menu', 'content'=>'1', 'extra'=>$wid]);
		$map = array(
			'wid'	=> $wid,
		);
		if ($fromKey) {
			$map['event_key'] = $fromKey;
		}
		$eventInfo = $this->eventDao->findMap($map);
		if (!$eventInfo) {
			return '';
		}
		db('Aaaa')->insert(['space'=>'weixin', 'module'=>'event', 'flag'=>'event_menu', 'content'=>'2', 'extra'=>$wid]);

		//是否带入openid参数
		if ($eventInfo['is_append_openid']) {
			$eventVerifyDao = model('weixin_manage/WeixinEventVerify');
			$eventVerifyDao->where(['wid'=>$wid, 'openid'=>$openid])->delete();
			$randnum = num_rand(20);
			$data = array(
				'wid'			=> $wid,
				'openid'		=> $openid, //用户标识id
				'randnum'		=> $randnum, //用户标识key
				'create_time'	=> time(),
			);
			$eventVerifyDao->baseAddData($data);
			$eventInfo['link'] = $eventInfo['link'].'&openid='.$openid.'&randnum='.$randnum;
		}
		db('Aaaa')->insert(['space'=>'weixin', 'module'=>'event', 'flag'=>'event_menu', 'content'=>'3', 'extra'=>$wid]);

		if ($eventInfo['event_msgtype'] == 1) { //文本
			$msg = $eventInfo['descrip'];
			return array('text', $msg);
		} else if ($eventInfo['event_msgtype'] == 2) { //图片
			$resultData = array(
				'media_id' => $eventInfo['media_id']
			);
			return array('image', $msg);
		} else if ($eventInfo['event_msgtype'] == 6) { //图文
			$newsData = array(
				'0' => array(
					'Title'	=> $eventInfo['title'],
					'PicUrl' => config('app.ftp_web').$eventInfo['picurl'],
					'Url' => $eventInfo['link'],
					'Description' => $eventInfo['descrip'],
				),
			);
			return array('news', '', $newsData);
		}
    }

    //微信文字回复获取关键字
    public function getEventByText($wid, $openid, $text = '') {
		$map = [
			'wid'		=> $wid,
			//'event_app'	=> 0,
			'isopen'	=> 1,
		];
		if ($text) {
			$map['event_text'] = $text;
		}
    	$eventInfo = $this->eventDao->findMap($map);
		db('Aaaa')->insert(['space'=>'weixin', 'module'=>'event', 'flag'=>'sql', 'content'=>showDbError($this->eventDao)]);
		db('Aaaa')->insert(['space'=>'weixin', 'module'=>'event', 'flag'=>'eventInfo', 'content'=>pw_var_export($eventInfo)]);

    	if (!$eventInfo) {
			//db('Aaaa')->insert(['space'=>'weixin', 'module'=>'event', 'flag'=>'getEventByText', 'content'=>'1.1']);
	    	//正则匹配
			$map = array(
				'wid'			=> $wid,
				//'event_app'		=> 1,
				'isopen'		=> 1,
			);
    		$eventList = $this->eventDao->where($map)->order('create_time DESC')->select();

    		$flag = $number = '';
    		foreach ($eventList as $key => $value) {
// 	    		$event_text = str_replace('{d}', '(\d+)', $value['event_text']);
				$event_text = $value['event_text'].'(\d+)';
				preg_match_all('/'.$event_text.'/is', $text, $matches);
				if ($matches[1]) {
					$flag = $value['event_text'];
					$number = $matches[1][0];
					continue;
				}
    		}

//     		if ($number) {
// 				$WpollService = new \Wap\Service\WpollWeixinService();
// 				list($code, $msg, $data) = $WpollService->weixinPoll($wid, $openid, $flag, $number);
// 				return array($code, $msg, $data);
// 			} else {
// 				//return array('text', 'event none');
//     		}

    		//比如，输入n1，弹出活动的图文信息
//     		if ($number) {
// 				$WpollDao = new \Wap\Model\WpollModel();
// 	    		$wpollInfo = $WpollDao->getInfoByWidAndFlag($wid, $flag);
// 	    		//print_r($wpollInfo);exit;
//
// 				$WpollItemDao = new \Wap\Model\WpollItemModel();
// 	    		$itemInfo = $WpollItemDao->getByPollIdAndNumber($wpollInfo['id'], $number);
//
// 				if ($wpollInfo['is_sec'] == 2 && $itemInfo['isopen'] == 1) { //二次投票的情况
// 					return array('text', '该选手未进入第二轮网络评选，欢迎下次参与！');
// 				}
//
// 				$config_global = F('config_global');
// 				$newsData = array(
// 					'0' => array(
// 						'Title'	=> $wpollInfo['title'],
// 						'PicUrl' => C('FTP_WEB').$itemInfo['img1'],
// 						'Url' => $config_global['site_host_wx'].U('wap/wpoll/detail', array('id'=>$itemInfo['id'])),
// 						'Description' => $itemInfo['expand1'],
// 					),
// 				);
// 				//print_r($newsData);exit;
//
// 				return array('news', $newsData);
//     		} else {
//     			return '';
//     		}
    		//print_r($number);exit;
    	} else {
			//是否带入openid参数
			if ($eventInfo['is_append_openid']) {
				$eventVerifyDao = model('weixin_manage/WeixinEventVerify');
				$eventVerifyDao->where(['wid'=>$wid, 'openid'=>$openid])->delete();
				$randnum = num_rand(20);
				$data = array(
					'wid'			=> $wid,
					'openid'		=> $openid, //用户标识id
					'randnum'		=> $randnum, //用户标识key
					'create_time'	=> time(),
				);
				$eventVerifyDao->baseAddData($data);
				$eventInfo['link'] = $eventInfo['link'].'&openid='.$openid.'&randnum='.$randnum;
			}

			if ($eventInfo['event_msgtype'] == 1) { //文本
				$msg = $eventInfo['descrip'];
				if ($msg) {
					return array('text', $msg);
				} else {
					return array('other');
				}
			} else if ($eventInfo['event_msgtype'] == 2) { //图片
				$resultData = array(
					'media_id' => $eventInfo['media_id']
				);
				return array('image', '', $resultData);
			} else if ($eventInfo['event_msgtype'] == 6) { //图文
				$resultData = array(
					'0' => array(
						'Title'	=> $eventInfo['title'],
						'PicUrl' => $eventInfo['picurl'],
						'Url' => $eventInfo['link'],
						'Description' => $eventInfo['descrip'],
					),
				);
				return array('news', '', $resultData);
			}
    	}
    }

    public function checkVerify($openid, $code) {

		$map = array(
			'openid' 		=> $openid,
		);
    	$verify = $this->PollVerify->where($map)->find();

    	if (!$verify) {
			$this->resultInfo = array('text', '非法投票操作！');
			return $this->resultInfo;
    	}
    	//if (time() - $verify['create_time'] > 60) {
			//$this->resultInfo = array('text', '超时！请在昆山论坛公众号对话框内，重新获取投票页面');
			//return $this->resultInfo;
    	//}

    	if ($code != $verify['code']) {
			$this->resultInfo = array('text', '非法投票操作！');
			return $this->resultInfo;
    	}

    }

	/**
	 * Get the current result
	 * @access public
	 * @return array
	 */
	public function getResult() {
		return $this->resultInfo;
	}
}